package band.wukong.practice.springboot.spring4.basic.el;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author wukong(wukonggg@139.com)
 */
@Configuration
@ComponentScan("band.wukong.practice.springboot.spring4.basic.el")
@PropertySource("classpath:band/wukong/practice/springboot/spring4/basic/el/el.properties")
public class ELConfigBean {

    private static final Logger logger = LoggerFactory.getLogger(ELConfigBean.class);

    @Value("I love you!")
    private String normal;

    @Value("#{ systemProperties['os.name'] }")
    private String osName;

    @Value("#{ T(java.lang.Math).random() * 100.0 }")
    private double randomNumber;

    @Value("#{ ELComponent.another }")
    private String fromAnother;

    @Value("${band.wukong.practice.springboot.spring4.basic.el.book.name}")
    private String bookName;

    @Value("classpath:band/wukong/practice/springboot/spring4/basic/el/el.properties")
    private Resource testFile;

    @Value("http://www.bing.com")
    private Resource testUrl;

    @Autowired
    private Environment env;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propsConf() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    /**
     * 注意：band.wukong.practice.springboot.spring4.basic.el.book.author要想拿到需要设env
     *
     * @throws IOException
     */
    public void print() throws IOException {
        System.out.println("============================================================");
        logger.info("normal = " + normal);
        logger.info("osName = " + osName);
        logger.info("randomNumber = " + randomNumber);
        logger.info("fromAnother = " + fromAnother);
        logger.info("bookName = " + bookName);
        logger.info("env.getProperty(\"band.wukong.practice.springboot.spring4.basic.el.book.author\") = " + env.getProperty("band.wukong.practice.springboot.spring4.config.el.book.author"));
        logger.info("IOUtils.toString(testFile.getInputStream()) = " + IOUtils.toString(testFile.getInputStream(), Charset.forName("UTF-8")));
        logger.info("IOUtils.toString(testUrl.getInputStream()) = " + IOUtils.toString(testUrl.getInputStream(), Charset.forName("UTF-8")));
        System.out.println("============================================================");
    }
}
